﻿using ExcelUtility;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Windows.Forms;
using YNCNumberSys.DbDal;
using YNCNumberSys.Entity;
using cadApp = Autodesk.AutoCAD.ApplicationServices.Application;
namespace YNCNumberSys
{
    public partial class OutExcelForm : Form
    {
        bool m_outBom = true;
        public bool OutBomExcel
        {
            get { return m_outBom; }
            set { m_outBom = value;
                buttonOut.Visible = value;
            }
        }
        bool m_outBomHoldonOld = true;
        public bool OutBomHoldonOld
        {
            get { return m_outBomHoldonOld; }
            set { m_outBomHoldonOld = value;
                buttonOutbomHoldonOld.Visible = value;}
        }
        string m_jch = string.Empty;
        public string Jch
        {
            get { return textBoxJch.Text; }
            set { textBoxJch.Text = value; }
        }
        string m_ah = string.Empty;
        public string Ah
        {
            get { return textBoxAh.Text; }
            set {textBoxAh.Text = value;}
        }

        private string m_user;
        public string User
        {
            get { return m_user; }
            set { m_user = value; }
        }
        public bool  Check4C
        {
            get { return checkBox4C.Checked; }
            set { checkBox4C.Checked = value; }
        }

        public OutExcelForm()
        {
            InitializeComponent();
        }
        private void buttonQuery_Click(object sender, EventArgs e)
        {
            DataTable newDataTable = null;
            if (checkBox4C.Checked)
            {
                PaperCodeDal dal = new PaperCodeDal();
                DataTable dt1 = dal.Get4CTitle(Jch, Ah);
                if (dt1 != null)
                {
                    if (dt1.Rows.Count > 0)
                    {
                        DataTable dt2 = dal.Get4C(Jch, Ah);
                        newDataTable = dt1.Clone();
                        object[] obj = new object[newDataTable.Columns.Count];
                        for (int i = 0; i < dt1.Rows.Count; i++)
                        {
                            dt1.Rows[i].ItemArray.CopyTo(obj, 0);
                            newDataTable.Rows.Add(obj);
                        }
                        if (dt2 != null)
                        {
                            for (int i = 0; i < dt2.Rows.Count; i++)
                            {
                                dt2.Rows[i].ItemArray.CopyTo(obj, 0);
                                newDataTable.Rows.Add(obj);
                            }
                        }
                        m_flex.DataSource = newDataTable;
                        if (m_flex.Cols.Contains("ID"))
                            m_flex.Cols["ID"].Visible = false;
                        for (int r = 1; r < m_flex.Rows.Count; r++)
                        {
                            m_flex[r, 0] = r;
                        }
                        m_flex.AutoSizeRows();
                        m_flex.AutoSizeCols();
                    }
                    else
                    {
                        MessageBox.Show("ZP-4C未分配，无法导出完整目录!", "提示");
                    }
                }
            }
            else
            {
                PaperCodeDal dal = new PaperCodeDal();
                DataTable dt1 = dal.GetZpTitle(Jch, Ah);
                if(dt1.Rows.Count>0)
                {
                    DataTable dt2 = dal.GetZP(Jch, Ah);
                    newDataTable = dt1.Clone();
                    object[] obj = new object[newDataTable.Columns.Count];
                    //添加DataTable1的数据
                    for (int i = 0; i < dt1.Rows.Count; i++)
                    {
                        dt1.Rows[i].ItemArray.CopyTo(obj, 0);
                        newDataTable.Rows.Add(obj);
                    }
                    for (int i = 0; i < dt2.Rows.Count; i++)
                    {
                        dt2.Rows[i].ItemArray.CopyTo(obj, 0);
                        newDataTable.Rows.Add(obj);
                    }
                    m_flex.DataSource = newDataTable;
                    if (m_flex.Cols.Contains("ID"))
                        m_flex.Cols["ID"].Visible = false;
                    for (int r = 1; r < m_flex.Rows.Count; r++)
                    {
                        m_flex[r, 0] = r;
                    }
                    m_flex.AutoSizeRows();
                    m_flex.AutoSizeCols();
                }
                else//没有装配图
                {
                    MessageBox.Show("没有装配图，无法导出完整目录!", "提示");
                }
            }
        }

        private void OutExcelForm_Load(object sender, EventArgs e)
        {
            buttonQuery_Click(null, null);
        }
        private void OutBom(bool saveold)
        {
            DataTable dt = (DataTable)m_flex.DataSource;
            if (dt == null) return;
            if (dt.Rows.Count < 1) return;
            string fileName=dt.Rows[0]["图纸编号"].ToString();
            string leixing=dt.Rows[0]["图纸类型"].ToString();
            string sName = /*leixing+*/fileName.PadLeft(6,'0');
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel(*.xls)|*.xls";//设置文件类型
            sfd.FileName = sName;//设置默认文件名
            sfd.DefaultExt = "xls";//设置默认格式（可以不设）
            sfd.AddExtension = true;//设置自动在文件名中添加扩展名
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string filePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                string fileNew = string.Empty;
                if (!saveold)
                {
                    string file = Path.Combine(Path.GetDirectoryName(filePath), @"xls\模板.xls");
                    fileNew = sfd.FileName;
                    File.Copy(file, fileNew, true);
                }
                else
                {
                    fileNew= sfd.FileName;
                }
                if (File.Exists(fileNew))
                {
                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            DataTable newDataTable = (DataTable)m_flex.DataSource;
                            List<PaperCodeEntity> Lst = new List<PaperCodeEntity>();
                            int maxNum = 0;
                            //第一条肯定为ZP
                            //第二条之后是实际的数
                            int count = dt.Rows.Count - 1;
                            for (int i = 1; i < dt.Rows.Count; i++)
                            {
                                string sLjxh = dt.Rows[i]["零件序号"].ToString();
                                if (sLjxh.Contains(","))
                                {
                                    string[] s = sLjxh.Split(',');
                                    for (int j = 0; j < s.Length; j++)
                                    {
                                        int iLjXH = -1;
                                        if (int.TryParse(s[j], out iLjXH))
                                        {
                                            PaperCodeEntity paperEntity = new PaperCodeEntity();
                                            paperEntity.Jcxh = dt.Rows[i]["机床型号"].ToString();
                                            paperEntity.Ah = dt.Rows[i]["A号"].ToString();
                                            paperEntity.Ljxh = dt.Rows[i]["零件序号"].ToString();
                                            paperEntity.Tzbh = dt.Rows[i]["图纸编号"].ToString();
                                            paperEntity.Mc = dt.Rows[i]["名称"].ToString();
                                            paperEntity.Gz = dt.Rows[i]["规格"].ToString();
                                            paperEntity.Zh = dt.Rows[i]["申请人"].ToString();
                                            paperEntity.Tzlx = dt.Rows[i]["图纸类型"].ToString();
                                            paperEntity.Num = iLjXH;
                                            Lst.Add(paperEntity);
                                            if (maxNum < iLjXH)
                                                maxNum = iLjXH;
                                        }
                                    }
                                }
                                else
                                {
                                    int iLjXH = -1;
                                    if (int.TryParse(dt.Rows[i]["零件序号"].ToString(), out iLjXH))
                                    {
                                        PaperCodeEntity paperEntity = new PaperCodeEntity();
                                        paperEntity.Jcxh = dt.Rows[i]["机床型号"].ToString();
                                        paperEntity.Ah = dt.Rows[i]["A号"].ToString();
                                        paperEntity.Ljxh = dt.Rows[i]["零件序号"].ToString();
                                        paperEntity.Tzbh = dt.Rows[i]["图纸编号"].ToString();
                                        paperEntity.Mc = dt.Rows[i]["名称"].ToString();
                                        paperEntity.Gz = dt.Rows[i]["规格"].ToString();
                                        paperEntity.Zh = dt.Rows[i]["申请人"].ToString();
                                        paperEntity.Tzlx = dt.Rows[i]["图纸类型"].ToString();
                                        paperEntity.Shr = dt.Rows[i]["审核人"].ToString();
                                        paperEntity.Num = iLjXH;
                                        Lst.Add(paperEntity);
                                        if (maxNum < iLjXH)
                                            maxNum = iLjXH;
                                    }
                                }
                            }
                            DataTable dtNew = dt.Clone();
                            DataRow dr = dtNew.NewRow();
                            dr["机床型号"] = dt.Rows[0]["机床型号"].ToString();
                            dr["A号"] = dt.Rows[0]["A号"].ToString();
                            dr["零件序号"] = dt.Rows[0]["零件序号"].ToString();
                            dr["图纸编号"] = dt.Rows[0]["图纸编号"].ToString();
                            dr["名称"] = dt.Rows[0]["名称"].ToString();
                            dr["规格"] = dt.Rows[0]["规格"].ToString();
                            dr["申请人"] = dt.Rows[0]["申请人"].ToString();
                            dr["图纸类型"] = dt.Rows[0]["图纸类型"].ToString();
                            dr["审核人"] = dt.Rows[0]["审核人"].ToString();
                            dr["ID"] = 1;
                            dtNew.Rows.Add(dr);
                            for (int i = 2; i <= maxNum + 1; i++)
                            {//建立一个空表
                                DataRow dr2 = dtNew.NewRow();
                                dr2["ID"] = i;
                                dtNew.Rows.Add(dr2);
                            }

                            for (int i = 0; i < Lst.Count; i++)
                            {
                                int iNo = Lst[i].Num;
                                DataRow[] dr2 = dtNew.Select(string.Format("ID={0}", iNo));
                                for (int j = 0; j < dtNew.Rows.Count; j++)
                                {
                                    if (iNo == (int)dtNew.Rows[j]["ID"])
                                    {
                                        dtNew.Rows[j]["机床型号"] = Lst[i].Jcxh;
                                        dtNew.Rows[j]["A号"] = Lst[i].Ah;
                                        dtNew.Rows[j]["零件序号"] = Lst[i].Ljxh;
                                        dtNew.Rows[j]["图纸编号"] = Lst[i].Tzbh;
                                        dtNew.Rows[j]["名称"] = Lst[i].Mc;
                                        dtNew.Rows[j]["规格"] = Lst[i].Gz;
                                        dtNew.Rows[j]["申请人"] = Lst[i].Zh;
                                        dtNew.Rows[j]["图纸类型"] = Lst[i].Tzlx;
                                        dtNew.Rows[j]["审核人"] = Lst[i].Shr;
                                        break;
                                    }
                                }
                            }
                            NpoiExcelHepler excelhepler = new NpoiExcelHepler();
                            string error = string.Empty;
                            if (saveold)
                            {
                                try
                                {
                                    error = excelhepler.OutExcelBomHoldOnOld(fileNew, dtNew);
                                }
                                catch (Exception ex)
                                {
                                    error = ex.Message;
                                }
                                finally
                                {
                                    if ("OK" != error)
                                        MessageBox.Show(error, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    else
                                        cadApp.ShowAlertDialog("完成明细表生成!");
                                }
                            }
                            else
                            {
                                try
                                {
                                    excelhepler.OutExcelBom(fileNew, dtNew);
                                }
                                catch (Exception ex)
                                {
                                    error = ex.Message;
                                }
                                finally
                                {
                                    if (!string.IsNullOrEmpty(error))
                                    {
                                        MessageBox.Show(error, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        
                                    }
                                    else
                                        cadApp.ShowAlertDialog("完成明细表生成!");
                                }
                            }
                        }
                    }
                }

            }
            else
            {
                this.Close();
            }
        }
        private void buttonOut_Click(object sender, EventArgs e)
        {
            OutBom(false);
        }

        private void buttonOut2_Click(object sender, EventArgs e)
        {
            OutBom(true);
        }
    }
}
